<?php

namespace App\Http\Controllers\Admin;

use App\Response\AdminRep;
use App\Response\TableRep;
use App\Services\AdminService\Models\AdminIconsModel;
use App\Services\AdminService\Models\AdminPermissionsModel;
use App\Services\AdminService\Models\AdminRoleModel;
use App\Services\AdminService\Models\AdminUserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
    use TableRep, AdminRep;

    /**
     * 后台布局
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function layout()
    {
        return view('admin.layout');
    }

    /**
     * 后台首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('admin.index.index');
    }

    public function index1()
    {
        return view('admin.index.index1');
    }

    public function index2()
    {
        return view('admin.index.index2');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 数据表格接口
     */
    public function data(Request $request)
    {
        $model = $request->get('model');
        switch (strtolower($model)) {
            case 'user':
                $query = new AdminUserModel();
                if (!empty($request->get('user_name'))) {
                    $query = $query->where('name', 'like', '%' . $request->get('user_name') . '%');
                }
                if (!empty($request->get('user_role'))) {
                    $query = $query->join('admin_model_has_roles', 'admin_model_has_roles.model_id', '=', 'id')
                        ->where("admin_model_has_roles.role_id", $request->get('user_role'));
                }
                break;
            case 'role':
                $query = new AdminRoleModel();
                break;
            case 'permission':
                $query = new AdminPermissionsModel();
                $query = $query->where('parent_id', $request->get('parent_id', 0))->with('icon');
                break;
            default:
                $query = new AdminUserModel();
                break;
        }
        $sorts = $request->get('sort');
        if ($sorts) {
            foreach ($sorts as $key => $value) {
                $query = $query->orderBy($key, $value);
            }
        }
        $res = $query->paginate($request->get('limit', 30))->toArray();
        return $this->table($res);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * 所有icon图标
     */
    public function icons()
    {
        $icons = AdminIconsModel::orderBy('sort', 'desc')->get();
        return $this->responseSucc($icons);
    }

}
